package com.faithnmn.learnenglish.service;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.faithnmn.learnenglish.MyApplication;
import com.faithnmn.learnenglish.db.DataBaseHelper;
import com.faithnmn.learnenglish.model.Quote;
import com.faithnmn.learnenglish.network.NetworkExecutor;
import com.faithnmn.learnenglish.util.Constants;
import com.faithnmn.utils.core.Core;
import com.faithnmn.utils.core.callbacks.GotConfigurationsCallback;
import com.faithnmn.utils.core.callbacks.GotNotificationsCallback;
import com.faithnmn.utils.core.model.Configurations;
import com.faithnmn.utils.core.model.Notification;

public class FeedService extends Service {
	private static boolean gettingData = false;
	private static NetworkExecutor networkExecutor;
	public static long previousGettingData;
	public static DataBaseHelper dbHelper;
	public static FeedService instance;
	private Handler handler = new Handler();
	private Core core;
	private static String CONFIGURATION_REQUEST_TAG = "cf_request_tag";
	private static String NOTIFICATION_REQUEST_TAG = "nt_request_tag";
	@Override
	public void onCreate() {
		super.onCreate();
		IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);        
		registerReceiver(networkStateReceiver, filter);
		networkExecutor = NetworkExecutor.getInstance().init(this);
		instance = this;
		core =  Core.getInstance().init(this);
		core.getConfigurations(CONFIGURATION_REQUEST_TAG, new GotConfigurationsCallback() {
			
			@Override
			public void onGotConfigurations(ArrayList<Configurations> configurations) {
				for(int i=0;i<configurations.size();i++){
					Configurations config = configurations.get(i);
					Log.e("appid","appid:"+config.udPId);
					if(config.udPId.equals(Constants.pkname)){
						Log.e(Constants.pkname,"pid:"+config.udPId);
						core.getNotifications(NOTIFICATION_REQUEST_TAG, config.udPId, "", new GotNotificationsCallback() {
							
							@Override
							public void onGotNotification(ArrayList<Notification> notifications) {
								
							}
						});
						break;
					}
				}
			}
		});
//		core.getn
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				checkingNewFeeds();
			}
		}, 3000);
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		checkingNewFeeds();
		return super.onStartCommand(intent, flags, startId);
	}
	
	public static FeedService getInstance(){
		if(instance == null){
			instance = new FeedService();
		}
		return instance;
	}
	
	public static void checkingNewFeeds(){
		if(MyApplication.getInstance() == null || MyApplication.getSharedPreferences() == null || gettingData){
			return;
		}
		previousGettingData = MyApplication.getSharedPreferences().getLong(Constants.LAST_UPDATE, 0);
		if(System.currentTimeMillis() < previousGettingData + 1000*60*60*1 || gettingData){
    		//Getting for each 1 hour
    		return;
    	}
		gettingData = true;
		Log.e("FeedService", "getting new feeds..");
		if(networkExecutor == null){
			networkExecutor = NetworkExecutor.getInstance().init(instance);
		}
		networkExecutor.getPagePostStatus(3000, new Listener<JSONObject>() {

			@Override
			public void onResponse(JSONObject response, String extraData) {
				previousGettingData = System.currentTimeMillis();
				MyApplication.getSharedPreferences().edit().putLong(Constants.LAST_UPDATE, previousGettingData).commit();
				Log.e("Response Success", response == null?"Response NULL":"Succeeded! Prepare to write db");
				ArrayList<Quote> quotes = new ArrayList<Quote>();
				try {
					JSONArray arr = response.getJSONArray("data");
					Quote quote;
					JSONObject jsonObj;
					for(int i=0;i<arr.length();i++){
						jsonObj = arr.getJSONObject(i);
						quote = new Quote(jsonObj.getString("post_id"), jsonObj.getString("created_time"), jsonObj.getString("message"));
						quotes.add(quote);
					}
					dbHelper = new DataBaseHelper(instance);
					ArrayList<String> updateList = dbHelper.insertQuotes(quotes);
					int insearted = updateList.size();
					if(insearted > 0){
						Intent feed = new Intent(FeedReceiver.ACTION);
						feed.putStringArrayListExtra("feeds", updateList);
						LocalBroadcastManager.getInstance(instance).sendBroadcast(feed);
					}
					arr = null;
				} catch (JSONException e) {
					e.printStackTrace();
				}
				Log.e("Response Success", "Succeeded! Writed to file");
				dbHelper = null;
				quotes = null;
				gettingData  = false;
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error, String extraData) {
				gettingData = false;
				Log.e("Response Error", error.getMessage() == null?"Error,try again":error.getMessage());
			}
		});
	}
	
	@Override
	public void onDestroy() {
		unregisterReceiver(networkStateReceiver);
		super.onDestroy();
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	private BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
		private boolean firstConnect = true;
	    @Override
	    public void onReceive(Context context, Intent intent) {
	    	final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	        final NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
	        if (activeNetInfo != null) {
	            if(firstConnect) { 
	                // do subroutines here
	            	Log.e("Network Listener", "Network Connected!");
	            	checkingNewFeeds();
	                firstConnect = false;
	            }
	        }
	        else {
	            firstConnect= true;
	        }
	    }
	};
}
